package com.abc.queue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayElements implements Delayed{

	
	private String key;
	
	private long aliveTime;
	
	private long timeOut;
	
	public String getKey() {
		return key;
	}
	public long getAliveTime() {
		return aliveTime;
	}
	public long getTimeOut() {
		return timeOut;
	}
	
	public void setKey(String key) {
		this.key = key;
	}
	public void setAliveTime(long aliveTime) {
		this.aliveTime = aliveTime;
	}
	public void setTimeOut(long timeOut) {
		this.timeOut = timeOut;
	}
	
	public DelayElements(String key, long aliveTime) {
		this.key = key;
		this.aliveTime = aliveTime;
		this.timeOut = TimeUnit.NANOSECONDS.convert(aliveTime, TimeUnit.SECONDS) + System.nanoTime();
	}
	@Override
	public int compareTo(Delayed o) {
		if (o == null) {
			return 1;
		}
		if (o == this) {
			return 0;
		}
		if (o instanceof DelayElements) {
			DelayElements de = (DelayElements) o;
			if (this.timeOut > de.getTimeOut()) {
				return 1;
			}else if (this.timeOut < de.getTimeOut()) {
				return -1;
			}
		}
		return 0;
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(timeOut - System.nanoTime(),  TimeUnit.NANOSECONDS);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime*result+((key == null) ? 0:key.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		DelayElements othre = (DelayElements) obj;
		if (key == null) {
			if (othre.key != null) {
				return false;
			}
		}else if (!key.equals(othre.key)) {
			return false;
		}
		return true;
	}

}
